/*
 * @Author: Haochen
 * @Date: 2021-11-19 18:09:30
 * @LastEditTime: 2021-11-29 11:55:39
 * @FilePath: \front\webpack.config.js
 */

var path = require('path'); //nodejs的内置模块，主要处理文件路径等问题
const HtmlWebpackPlugin = require('html-webpack-plugin');
const loader = require('sass-loader');

/*
 * 新页面操作：
 * entry(js)
 * plugins(html)
 * 在src的操作：
 * html
 * js
 * scss
 */
module.exports = {
  mode: 'development',
  // *输入配置
  entry: {
    //设置index.html要打包的入口js文件
    index: './src/js/index.js',
    register: './src/js/register.js',
    login: './src/js/login.js',
    exam: './src/js/exam.js',
    exam_info: './src/js/exam_info.js',
    exam_paper: './src/js/exam_paper.js',
    exam_score: './src/js/exam_score.js',
    exam_detail: './src/js/exam_detail.js',
  },
  // *输出配置
  output: {
    //输出文件位置
    path: path.resolve(__dirname, 'dist/'),
    //文件名保持一致
    filename: 'js/[name].js',
  },
  // *插件配置
  plugins: [
    htmlPlugin('index'),
    htmlPlugin('register'),
    htmlPlugin('login'),
    htmlPlugin('exam'),
    htmlPlugin('exam_info'),
    htmlPlugin('exam_paper'),
    htmlPlugin('exam_score'),
    htmlPlugin('exam_detail'),
  ],
  module: {
    rules: [
      // 打包css文件
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      // 打包scss文件
      {
        test: /.scss$/i,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
      // 打包图片
      {
        test: /\.(png|jpg|jpeg|gif|webp)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 1024 * 12, //10kb (10 * 1024 bytes)
              outputPath: './img/',
              esModule: false,
              name: '[hash:10].[ext]',
            },
          },
        ],
      },
      // 打包html文件
      {
        test: /\.html$/i,
        use: ['html-withimg-loader'],
      },
      {
        test: /\.(ttf|eot|svg|woff|woff2)$/,
        use: 'file-loader',
      },
      {
        test: /\.(mp3)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          name: 'audios/[name].[ext]',
          limit: 10,
        },
      },
    ],
  },
  // *服务器配置
  devServer: {
    port: 8888, //服务器端口号，默认8080
    open: true, // 启动服务器时自动打开页面
    hot: true, // 实时更新,即保存代码时自动打包
    openPage: 'html/register.html', //启动服务器后自动打开的页面路径，dist目录为起点
    proxy: {
      '/': {
        target: 'http://localhost:10088', // 后端服务器地址
      },
    },

    // headers: {
    //   'Access-Control-Allow-Origin': 'http://localhost:10088',
    // },
  },
};

function htmlPlugin(htmlName) {
  return new HtmlWebpackPlugin({
    template: `./src/html/${htmlName}.html`,
    filename: `./html/${htmlName}.html`,
    chunks: [htmlName],
  });
}
